package org.linlinjava.litemall.admin.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.dao.WxMsgReplyMerchantMapper;
import org.linlinjava.litemall.db.domain.LitemallShop;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.domain.LitemallUserBalance;
import org.linlinjava.litemall.db.domain.LitemallUserExample;
import org.linlinjava.litemall.db.domain.WxMsgReplyMerchant;
import org.linlinjava.litemall.db.domain.WxMsgReplyMerchantExample;
import org.linlinjava.litemall.db.service.LitemallShopService;
import org.linlinjava.litemall.db.service.LitemallUserBalanceService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.util.UserTokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import javax.validation.constraints.NotNull;

@RestController
@RequestMapping("/admin/user")
@Validated
public class AdminUserController {
    private final Log logger = LogFactory.getLog(AdminUserController.class);

    @Autowired
    private LitemallUserService userService;
    @Autowired
    private LitemallUserBalanceService userBalanceService;
    @Autowired
    private LitemallShopService shopService;
    @Autowired
    private WxMsgReplyMerchantMapper merchantMapper;

    @RequiresPermissions("admin:user:list")
    @RequiresPermissionsDesc(menu = {"用户管理", "会员管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String username, String mobile,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<LitemallUser> userList = userService.querySelective(username, mobile, page, limit, sort, order);
        return ResponseUtil.okList(userList);
    }
    
    @RequiresPermissions("admin:user:detail")
    @RequiresPermissionsDesc(menu = {"用户管理", "会员管理"}, button = "详情")
    @GetMapping("/detail")
    public Object userDetail(@NotNull Integer id) {
    	LitemallUser user=userService.findById(id);
        return ResponseUtil.ok(user);
    }
    
    @RequiresPermissions("admin:user:update")
    @RequiresPermissionsDesc(menu = {"用户管理", "会员管理"}, button = "修改")
    @PostMapping("/update")
    public Object userUpdate(@RequestBody LitemallUser user) {
    	LitemallUser u = userService.findById(user.getId());
    	if(u.getShopId() > 0) {
    		return ResponseUtil.custom("用户已绑定有门店，不允许操作！");
    	}
    	int row = userService.updateById(user);
    	if(row > 0) {
    		//生成用户余额表记录
    		userBalanceService.insertUserBalance(user);
    		//修改门店表userID
    		LitemallShop shop = new LitemallShop();
    		/*
    		shop.setUserId(user.getId());
    		shop.setId(user.getShopId());
    		shopService.updateById(shop);*/
    		//更改完成后，强制在线用户下线（原理：更换后端 token，导致小程序与后端token不一致，从而达到让用户重新登录获取信息目的）
    		UserTokenManager.generateToken(user.getId());
    		return ResponseUtil.ok(row);
    	}
    	return ResponseUtil.custom("门店ID已绑定其他用户！");
    }
    
    @RequiresPermissions("admin:user:createReplyMerchant")
    @RequiresPermissionsDesc(menu = {"用户管理", "会员管理"}, button = "绑定")
    @PostMapping("/createReplyMerchant")
    public Object createReplyMerchant(@RequestBody LitemallUser user) {
    	/*
    	LitemallUser u = userService.findById(user.getId());
    	if(u.getShopId() > 0) {
    		return ResponseUtil.custom("用户已绑定有门店，不允许操作！");
    	}*/
    	if(user.getShopId() == null) {
    		return ResponseUtil.custom("参数有误！");
    	}
    	WxMsgReplyMerchantExample example = new WxMsgReplyMerchantExample();
    	WxMsgReplyMerchantExample.Criteria criteria = example.createCriteria();
    	criteria.andShopIdEqualTo(user.getShopId());
    	WxMsgReplyMerchant rm = merchantMapper.selectOneByExample(example);
    	if(rm != null) {
    		return ResponseUtil.custom("门店已绑定！");
    	}
    	//添加记录
    	WxMsgReplyMerchant wrmc = new WxMsgReplyMerchant();
    	wrmc.setShopId(user.getShopId());
    	wrmc.setUnionId(user.getUnionid());
    	//wrmc.setMiniAppOpenId(user.getWeixinOpenid());
    	wrmc.setMpOpenId(user.getWeixinOpenid());
    	merchantMapper.insertSelective(wrmc);
    	return ResponseUtil.ok();
    }
}
